<template>
	<view class="page-custom-photo-operator photo-operator" :class="[`busi-${busiType}`]">
		<view class="fixed-top-tab">
			<switch-tab v-if="couldPrint" :current="currentTab" :list="topTabs" @change="onTopTabChange"></switch-tab>
		</view>
		<view class="top-container flex-center">
			<template v-if="photoUrl">
				<!-- 单张 -->
				<view v-if="currentTab === 0" class="photo-wrap">
					<text class="photo-witdh">{{ detailInfo.widthPixel }}px</text>
					<text class="photo-height">{{ detailInfo.heightPixel }}px</text>
					<image class="photo-image" :style="photoImageStyle" :src="photoUrl" mode="aspectFit"></image>
				</view>
				<!-- 排版照 -->
				<view v-else class="typeset-photo-wrap">
					<image class="typeset-photo-image" :src="typesetUrl"></image>
				</view>

				<view class="reupload-button custom-button white-btn-gray-text" @tap="onChoosePhoto">
					<u-button type="primary" shape="circle" text="重新上传"></u-button>
				</view>

			</template>
			<template v-else>
				<view class="upload-box" @tap="onChoosePhoto">
					<text class="add-icon">+</text>
					<view class="add-text">点击上传你的照片</view>
				</view>
			</template>
			<artificial-beauty />

		</view>

		<view v-if="busiType === 'photo-print-credit'" class="field-container">
			<view class="normal-title-16 flex-center">
				效果生成成功！
			</view>
			<view class="custom-button full-button" @tap="onPrintMail">
				<u-button type="primary" shape="circle" text="冲印邮寄"></u-button>
			</view>
		</view>
		<view v-else class="field-container">
			<view class="tab-container">
				<view class="flex-center normal-title-16">
					<view class="">选择底色</view>
					<view class="beauty-box flex-start-center-gap-10">
						<text>美颜</text>
						<view class="beauty-switch">
							<u-switch key="switch-beauty" size="24" v-model="currentBeauty" :activeValue="1"
								:inactiveValue="0" activeColor="#4591E6" space="2" @change="onBeautyChange"></u-switch>
						</view>
					</view>
				</view>
				<!-- <u-tabs :list="tabs" :scrollable="false" :current="currentFuncIdx" @change="onTabChange"
					lineWidth="28"  itemStyle="width:340rpx;height:66rpx;box-sizing:border-box;align-items: flex-start;"></u-tabs> -->
			</view>
			<view v-show="currentFuncIdx === 0" class="choose-color-container">
				<choose-color :current="backColor" :onColorChange="onColorChange"
					@backColorListChange="onBackColorListChange" />
			</view>
			<!-- <view v-show="currentFuncIdx === 1" class="beauty-list-container">
				<beauty-list :current="currentBeauty" :list="beautylist" @change="onBeautyChange" />
			</view> -->
			<view class="btn-double">
				<view class="custom-button full-button" @tap="onSavePhoto">
					<u-button type="primary" shape="circle" text="保存电子照"></u-button>
				</view>
				<!-- #ifndef MP-TOUTIAO -->
					<view v-if="couldPrint" class="custom-button full-button" @tap="onPrintMail">
						<u-button type="primary" shape="circle" text="冲印邮寄"></u-button>
					</view>
				<!-- #endif -->
			</view>
		</view>
	</view>

	<view style="visibility: hidden;position: fixed; top: 200vh">
		<image :src="tempImage" @load="onImageLoad"></image>
	</view>
</template>
<script setup>
	import {
		onLoad,
		onReachBottom,
	} from '@dcloudio/uni-app';
	import {
		ref,
		reactive,
		computed,
	} from "vue";
	import ArtificialBeauty from '@/components/artificial-beauty/artificial-beauty.vue';
	import ChooseColor from '@/components/choose-color/choose-color.vue';
	import BeautyList from '@/components/beauty-list/beauty-list.vue';
	import SwitchTab from '@/components/switch-tab/index.vue';
	import {
		uploadFile
	} from '@/common/js/method';
	import {
		backColorList as fixedBackColorList
	} from '@/common/js/data.js';

	const currentBeauty = ref(1); // 0：无美颜， 1：超清美颜
	const busiType = ref('make-photo');
	const userImage = ref('');
	const tempImage = ref('');
	const photoUrl = ref('');
	const typesetUrl = ref('');
	const photoKeys = ref({});
	const beautyPhotoKeys = ref({});
	const photoUrls = ref({});
	const typesetUrls = ref({});
	const beautyPhotoUrls = ref({});
	const beautyTypesetUrls = ref({});
	const currentTab = ref(0);

	const detailInfo = ref({});
	const backColor = ref('#FFFFFF');
	const backgroundList = ref(fixedBackColorList.map(c => c.background));
	const topTabs = ['单张', '排版照'];
	const tabs = [{
			name: '选择底色',
		}, {
			name: '一键美颜',
		},
		// {
		// 	name: '换装'
		// },
	];
	const beautylist = [{
		id: '1',
		text: "无美颜",
		img: '/static/other/no-choose.png',
		activeImg: '/static/other/no-choose-active.png',
	}, {
		id: '2',
		text: "超清美颜",
		img: '/static/other/beauty.png',
		activeImg: '/static/other/beauty-active.png',
	}];

	// 是否支持冲印邮寄
	const couldPrint = computed(() => {
		// 自定义照片不支持冲印邮寄
		if (busiType.value === 'custom') {
			return false;
		} else if (busiType.value === 'make-photo') { //证件照制作，根据上个页面的标识判断
			return detailInfo.value.couldPrint;
		}
		return true;
	});

	const photoImageStyle = computed(() => {
		const width = +detailInfo.value.widthPixel;
		const height = +detailInfo.value.heightPixel;
		let large = width > height ? width : height; //取较长的一边
		let scale = large < 250 ? 1 : 250 / large; //较长边大于250px则缩放，另一边也按该比例缩放
		return {
			width: width * scale + 'px',
			height: height * scale + 'px',
		}
	})


	const onImageLoad = async (e) => {
		// 如果是自定义,且用户没有设置大小
		if (+e.detail.width > 2000 || +e.detail.height > 2000) {
			uni.$u.toast('图片宽/高过大，不能超过2000px')
			return;
		}
		uni.showLoading({
			title: '处理中'
		});
		userImage.value = await uploadFile(tempImage.value);
		// 预览图片(默认美颜)
		await beauty();
		// 
		uni.hideLoading();
	}

	const resetImageCache = () => {
		currentBeauty.value = 1;// 默认美颜
		photoUrls.value = {};
		typesetUrls.value = {};
		beautyPhotoUrls.value = {};
		beautyTypesetUrls.value = {};
		photoKeys.value = {};
		beautyPhotoKeys.value = {};
		detailInfo.value.photoKey = null;
		detailInfo.value.beautyPhotoKey = null;
	}

	const onChoosePhoto = () => {
		uni.chooseImage({
			count: 1, //默认9
			sizeType: ['compressed'], //可以指定是原图还是压缩图，默认二者都有
			// sourceType: ['album'], //从相册选择
			success: function(res) {
				// image加载tempImage并读取宽高，进行校验后再上传 => onImageLoad
				resetImageCache();
				tempImage.value = res.tempFilePaths[0];
			}
		});
	};

	const setPhotoUrlByColor = async () => {
		// 超清美颜
		if (currentBeauty.value === 1) {
			if (beautyPhotoUrls.value[backColor.value]) {
				photoUrl.value = beautyPhotoUrls.value[backColor.value];
				typesetUrl.value = beautyTypesetUrls.value[backColor.value];
				detailInfo.value.beautyPhotoKey = beautyPhotoKeys.value[backColor.value]; //保存用于支付页接口使用
			} else { // 如果当前背景色的m美颜图片不存在，调预览接口查询
				// 超清美颜
				await beauty();
			}

		} else { // 无美颜
			if (photoUrls.value[backColor.value]) {
				photoUrl.value = photoUrls.value[backColor.value];
				typesetUrl.value = typesetUrls.value[backColor.value];
				detailInfo.value.photoKey = photoKeys.value[backColor.value]; //保存用于支付页接口使用
			} else { // 如果当前背景色的图片不存在，调预览接口查询
				await preview(backColor.value);
			}

		}


	}

	// 获取颜色列表
	const onBackColorListChange = (list) => {
		console.log('onBackColorListChange', list)
		backgroundList.value = list.map(item => item.background);
	}

	const onBeautyChange = (index) => {
		currentBeauty.value = index;
		// 无美颜
		if (index === 0) {
			// 设置回原来的图片
			setPhotoUrlByColor();
		} else if (index === 1) {
			setPhotoUrlByColor();
		}
	}

	// 美颜
	const beauty = async (color) => {
		const data = detailInfo.value;
		const payload = busiType.value === 'custom' ? {
			specId: 12, //自定义照片id固定送12
			width: data.widthPixel,
			height: data.heightPixel,
			imageUrl: userImage.value,
			bkColor: color || backgroundList.value.join(','),
			fileSize: [data.minSize, data.maxSize].join(','),
		} : {
			specId: data.specId,
			width: data.widthPixel,
			height: data.heightPixel,
			imageUrl: userImage.value,
			bkColor: color || backgroundList.value.join(','),
			fileSize: [data.minSize, data.maxSize].join(','),
		}
		const res = await uni.$request('/api/busi/photo/faceBeauty', payload);
		beautyPhotoUrls.value = {
			...beautyPhotoUrls.value,
			...res.data.previewUrls
		};
		beautyTypesetUrls.value = {
			...beautyTypesetUrls.value,
			...res.data.typesetUrls
		};
		// 缓存美颜照片的key
		Object.keys(beautyPhotoUrls.value).forEach((color) => {
			beautyPhotoKeys.value[color] = res.data.photoKey; // 保存颜色与key对应关系
		})
		photoUrl.value = beautyPhotoUrls.value[backColor.value];
		typesetUrl.value = beautyTypesetUrls.value[backColor.value];
		detailInfo.value.beautyPhotoKey = beautyPhotoKeys.value[backColor.value]; //保存用于支付页接口使用
		// console.log('美颜接口', res.data);
	};


	// 证件照预览接口
	const preview = async (color) => {
		color = color || backgroundList.value.join(',')
		if (!userImage.value) {
			return;
		}
		const data = detailInfo.value;
		const payload = busiType.value === 'custom' ? {
			specId: 12, //自定义照片id固定送12
			width: data.widthPixel,
			height: data.heightPixel,
			fileSize: [data.minSize, data.maxSize].join(','),
			dpi: data.dpi,
			imageUrl: userImage.value,
			bkColor: color,
		} : {
			specId: data.specId,
			imageUrl: userImage.value,
			bkColor: color,
			width: data.widthPixel,
			height: data.heightPixel,
			fileSize: [data.minSize, data.maxSize].join(','),
		}
		const res = await uni.$request('/api/busi/photo/preview', payload);
		photoUrls.value = {
			...photoUrls.value,
			...res.data.previewUrls
		};
		typesetUrls.value = {
			...typesetUrls.value,
			...res.data.typesetUrls
		};
		// 缓存普通照片的key
		Object.keys(photoUrls.value).forEach((color) => {
			photoKeys.value[color] = res.data.photoKey; // 保存颜色与key对应关系
		})
		photoUrl.value = photoUrls.value[backColor.value];
		typesetUrl.value = typesetUrls.value[backColor.value];
		detailInfo.value.photoKey = photoKeys.value[backColor.value]; //保存用于支付页接口使用
	}


	const onTopTabChange = (index) => {
		currentTab.value = index;
	}

	// 检查是否已缓存该颜色图片（区分美颜和无美颜存储）
	const getPhotoUrlByColor = (color) => {
		let res = null;
		// 超清美颜
		if (currentBeauty.value === 1 && beautyPhotoUrls.value[color]) {
			res = {
				photoUrl: beautyPhotoUrls.value[color],
				typesetUrl: beautyTypesetUrls.value[color],
			}
		} else if (currentBeauty.value === 0 && photoUrls.value[color]) { // 无美颜
			res = {
				photoUrl: photoUrls.value[color],
				typesetUrl: typesetUrls.value[color],
			}
		}
		return res;
	}

	const onColorChange = async (value) => {
		backColor.value = value;
		// 如果已存在该颜色图片，直接设置
		if (getPhotoUrlByColor(value)) {
			setPhotoUrlByColor();
		} else { //否则为新增的自定义颜色，调用美颜接口
			beauty(value);
		}
	}

	onLoad(async (params) => {
		console.log('onload', params);
		const data = JSON.parse(params.data);
		data.photoUrl = decodeURIComponent(data.photoUrl);
		// 动态设置标题
		uni.setNavigationBarTitle({
			title: data.name,
		});
		busiType.value = params.type;
		userImage.value = data.photoUrl;
		// 异步执行，兼容快手（detailInfo直接赋值会导致currentBeauty的值变为backgroundList的值）
		setTimeout(async () => {
			detailInfo.value = data;
			// 证件照打印，自带背景颜色
			if (params.type === 'photo-print-credit') {
				backColor.value = data.background;
				currentBeauty.value = 0;
				// 不美颜
				await preview();
			} else {
				// 证件照制作默认美颜
				await beauty();
			}
		}, 200)

	})
	const onSavePhoto = async () => {
		if (!userImage.value) return;
		let photoUrl = photoUrls.value[backColor.value];
		let photoKey = photoKeys.value[backColor.value];
		if (!photoKey) {
			await preview(backColor.value); //如果没有取消美颜，调一下无美颜的预览接口
			photoUrl = photoUrls.value[backColor.value];
			photoKey = photoKeys.value[backColor.value];
		}
		const beautyPhotoUrl = beautyPhotoUrls.value[backColor.value];
		const beautyTypesetUrl = beautyTypesetUrls.value[backColor.value];
		const data = {
			...detailInfo.value,
			photoKey,
			backColor: backColor.value, //背景色
			photoUrl: encodeURIComponent(photoUrl), //单张照(无美颜)
			typesetUrl: encodeURIComponent(beautyTypesetUrl), //排版照（默认为美颜后的）
			beautyPhotoUrl: encodeURIComponent(beautyPhotoUrl), //单张照(美颜)
		};
		console.log('data', data)
		uni.navigateTo({
			url: `/pages/make-photo/make-photo-save?type=${busiType.value}&data=${JSON.stringify(data)}`
		})

	}

	const onPrintMail = () => {
		if (!userImage.value) return;
		const typesetUrl = getPhotoUrlByColor(backColor.value).typesetUrl;
		const data = {
			...detailInfo.value,
			photoKey: currentBeauty.value ? detailInfo.value.beautyPhotoKey : detailInfo.value.photoKey,
			backColor: backColor.value, //背景色
			typesetUrl: encodeURIComponent(typesetUrl), //排版照
		};
		console.log('data', data);
		uni.navigateTo({
			url: `/pages/make-photo/make-photo-print?type=${busiType.value}&data=${JSON.stringify(data)}`
		})
	}
	const currentFuncIdx = ref(0);

	const onTabChange = ({
		index,
		...tabItem
	}) => {
		currentFuncIdx.value = index;
		if (index === 0) {

		} else if (index === 1) {

		} else if (index === 2) {
			uni.$u.toast('')
		}
	}
	const handleContact = () => {

	}
</script>
<style lang="scss" scoped>
	@import "@/common/style/photo-operator.scss";

	.page-custom-photo-operator {
		// min-height: 100vh;
		// padding-bottom: 510rpx;

		// 证件照打印特殊样式修改
		&.busi-photo-print-credit {
			// padding-bottom: 340rpx;

			.top-container {
				height: calc(100vh - 340rpx);
			}

			.field-container {
				padding-top: 32rpx;
				height: 340rpx;

			}
		}

		.beauty-box {
			margin-left: 80rpx;
		}

	}
</style>